package com.zzyl.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description WechatServiceImpl
 * @Author Lwj
 * @Date 2024-08-30-20:52
 */
@Service
public class WechatServiceImpl implements WechatService {

    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${zzyl.wechat.appId}")
    private String appId;

    @Value("${zzyl.wechat.appSecret}")
    private String secret;


    /**
     * 获取OpenId
     *
     * @param code 登录凭证
     * @return
     */
    @Override
    public String getOpenId(String code) {
        //封装参数
        Map<String, Object> requestUrlParam = new HashMap<>();
        requestUrlParam.put("js_code", code);
        requestUrlParam.put("appid", appId);
        requestUrlParam.put("secret", secret);
        //使用hutool工具远程调用返回json字符串
        String result = HttpUtil.get(REQUEST_URL, requestUrlParam);
        //把json字符串封装为JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断有没有errcode，如果没有那就是响应失败了
        if (ObjectUtil.isNotEmpty(jsonObject.get("errcode"))) {
            throw new BaseException(BasicEnum.GET_OPENID_ERROR);
        }
        //如果包含errcode就返回openId
        return jsonObject.get("openid").toString();
    }

    /**
     * 获取手机号
     *
     * @param code
     * @return
     */
    @Override
    public String getPhone(String code) {
        Map<String, Object> requestUrlParam = new HashMap<>();
        //需要获取Token
        String token = getToken();
        String url = PHONE_REQUEST_URL + token;
        requestUrlParam.put("code", code);
        //发送请求
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(requestUrlParam));
        //解析
        JSONObject jsonObject = JSONUtil.parseObj(result);
        //判断errcode是否为0(0是正确的）
        if (jsonObject.getInt("errcode") != 0) {
            throw new BaseException(BasicEnum.GET_PHONE_ERROR);
        }
        return jsonObject.getJSONObject("phone_info").get("purePhoneNumber").toString();
    }

    public String getToken() {
        Map<String, Object> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", appId);
        requestUrlParam.put("secret", secret);
        //转为Json字符串的格式
        String JsonString = HttpUtil.get(TOKEN_URL, requestUrlParam);
        //把json字符串封装为JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(JsonString);
        //如果code存在，则失败
        if (ObjectUtil.isNotEmpty(jsonObject.get("errcode"))) {
            throw new BaseException(BasicEnum.GET_TOKEN_ERROR);
        }
        return jsonObject.get("access_token").toString();
    }
}
